package com.mulanweb.handler;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.mulanweb.api.module.controller.ChatHistoryController;
import com.mulanweb.api.module.controller.admin.UserController;
import com.mulanweb.api.module.controller.wechat.TextMsgController;
import com.mulanweb.api.module.model.*;
import com.mulanweb.db.common.Constant;
import com.mulanweb.db.common.WxErrorCode;
import com.mulanweb.db.common.WxParaFormatter;
import com.mulanweb.handler.wechat.*;
import com.mulanweb.utils.AseUtils;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.select.Elements;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.*;


//import com.thoughtworks.xstream.XStream;

/**
 * Created by Administrator on 2016/8/9.
 */
public class WxManagerController extends Controller {

    private String Token = "zenghf521";

   /* public void temp(){
        List<PhotographyVoteCount> list = PhotographyVoteCount.dao.find("SELECT * FROM photography_vote_count WHERE user_id IN (SELECT id FROM `user` " +
                "WHERE id IN (SELECT user_id FROM photography_vote_count WHERE target_id = 10 ) AND logo_path = '' )");
        int i = 0 ;
        int e = 0 ;
        int t = 0 ;
        for(PhotographyVoteCount user : list){
            if(user.delete()){
                System.out.println("已删除:"+i);
                i++;
            }else{
                System.out.println("-------错误:"+e);
                e++;
            }
            t++;
        }
        System.out.println("-------共计处理:"+t);
        System.out.println("已删除:"+i);
        System.out.println("-------错误:"+e);
    }*/

    /*
        //懒猫数据爬虫
        public void lanmao() throws IOException {
            int pageNumber = 1;
            // String home = "https://lmlxhwd.alitrip.com/search.htm?spm=a1z10.1-b-s.w11422135-14856052041.8.CIsouK&search=y&scene=taobao_shop";
            //String home = "https://lmlxhwd.alitrip.com/i/asynSearch.htm?_ksTS=1489398943387_287&callback=jsonp288&mid=w-14844646096-0&wid=14844646096&path=/search.htm&&search=y&spm=a1z10.1-b-s.w11422135-14856052041.8.CIsouK&scene=taobao_shop";
            String home = "https://lmlxhwd.alitrip.com/i/asynSearch.htm?_ksTS=1489401323463_287&callback=jsonp288&mid=w-14844646096-0&wid=14844646096&path=/search.htm&&search=y&spm=a1z10.3-b-s.w4011-14844646096.277.HOmLkG&scene=taobao_shop&pageNo=_pageNumber_&tsearch=y".replace("_pageNumber_", pageNumber + "");
            org.jsoup.nodes.Document doc = Jsoup.connect(home).timeout(10000).get();
            int i = 0 ;
            int f = 0 ;
            while (doc.html() != null && pageNumber<10) {
                Elements elements = doc.select("dl");
                for (org.jsoup.nodes.Element e : elements) {
                    String zong_xiao_liang = e.select("dd").get(0).select("span").get(2).text();
                    String price = e.select("span").get(1).text();
                    String url = e.select("a").attr("href").replace("\"", "").replace("\\", "");
                    url = "https:"+url;

                    //开始 保存
                    org.jsoup.nodes.Document doc1 = Jsoup.connect(url).timeout(30000).get();
                    String name = doc1.getElementById("J_PropertyWrap").select("h1").get(0).text().replace("懒猫旅行","").trim() ;
                    String yuexiaoliang = doc1.getElementById("J_SellCountWrap").select("em").text();

                    Lanmao lanmao = new Lanmao();
                    lanmao.setName(name);
                    lanmao.setPrice(price);
                    lanmao.setUrl(url);
                    lanmao.setXiaoliang(yuexiaoliang);
                    lanmao.setZongxiaoling(zong_xiao_liang);
                    if(lanmao.save()){
                        i++;
                        System.out.println("成功保存："+ i +"条产品信息");
                    }else{
                        f++;
                        System.out.println("---失败："+ f +"条产品信息");
                    }
                }

                pageNumber++;
                home = "https://lmlxhwd.alitrip.com/i/asynSearch.htm?_ksTS=1489401323463_287&callback=jsonp288&mid=w-14844646096-0&wid=14844646096&path=/search.htm&&search=y&spm=a1z10.3-b-s.w4011-14844646096.277.HOmLkG&scene=taobao_shop&pageNo=_pageNumber_&tsearch=y".replace("_pageNumber_", pageNumber + "");
                doc = Jsoup.connect(home).timeout(30000).get();
            }
        }
    */
    /*private Integer getRandom(Integer disanceRest, Integer restClick) {
        Integer pingJun = disanceRest / restClick;
        Float percent = 0.3F;
        Random random = new Random();
        int max = Math.round(pingJun + pingJun * percent);
        int min = Math.round(pingJun - pingJun * percent);
        System.out.println(max);
        System.out.println(min);
        int value = random.nextInt(max) % (max - min + 1) + min;
        return value;
    }

    private boolean isActiveUser(User user) {
        return !(null != user || user.getStatusId() == 1);
        //return null != user && user.getStatusId() == 1;
    }
    private boolean isActiveEvent(EventAttend eventAttend) {
        if (null == eventAttend) {
            return false;
        }
        Event event = Event.dao.findFirst("SELECT * FROM event WHERE id =? AND start_time <= NOW() AND NOW() < end_time", eventAttend.getEventId());
        if (event == null) {
            return false;
        }
        return false;

    }

    protected void renderData(int code, String message) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", code);
        map.put("message", message);
        renderJson(map);
    }

    private static synchronized void update(WxManagerController controller, User user, Integer eventId) {
        EventAttend eventAttend = EventAttend.dao.findById(eventId);
        if (controller.isActiveEvent(eventAttend)) {
            controller.renderData(0, "活动已结束,或未开始！");
            return;
        }
        EventSustain eventSustain_ = EventSustain.dao.findFirst("SELECT * FROM event_sustain WHERE user_id = ?", user.getId());
        //判断投票者是存在投票次数，投票次数为一
        if (eventSustain_ != null) {
            //提示用户已无投票权
            controller.renderData(0, "每人仅能给一位好友加油哦！送您一张满1000减50优惠券(券码:" + Constant.Event.COUPON_CODE + ")");
            return;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        //剩余点击次数
        int restClickAmount = eventAttend.getRestClickAmount();
        //随机里程数
        Integer value = 0;
        if (restClickAmount == 1) {
            //得出最后里程数，结束投票，更新完成投票时间
            value = eventAttend.getDisanceRest();
        } else if (restClickAmount > 0) {
            //开始 计算 随机里程参与投票
            value = controller.getRandom(eventAttend.getDisanceRest(), eventAttend.getRestClickAmount());
        } else if (restClickAmount < 0) {
            controller.renderData(0, "已超过投票次数，投票无效");
            return;
        } else {
            //投票已完成
            controller.renderData(0, "投票已结束");
            return;
        }
        final int oValue = value;
        EventSustain eventSustain = new EventSustain();
        eventSustain.setUserId(user.getId());
        eventSustain.setAttendId(eventAttend.getId());
        eventSustain.setValue(value);
        eventSustain.setCreateTime(new Date());

        boolean state = Db.tx(()->{
            if(eventSustain.save()) {
                eventAttend.setRestClickAmount(restClickAmount - 1);
                Integer tag = eventAttend.getDisanceRest() - oValue;
                if (tag <= 0) {
                    tag = 0;
                    eventAttend.setCompleteTime(new Date());
                }
                eventAttend.setDisanceRest(tag);
                return eventAttend.update();
            }
            return false;
        });

        if (state) {
            //提示投票成功
            User targetUser = User.dao.findById(eventAttend.getUserId());

            map.put("value", eventSustain.getValue());
            map.put("username", targetUser.getWechatNickname());
            map.put("couponCode", Constant.Event.COUPON_CODE);//安慰奖
            map.put("code", 1);//操作结果代码
            controller.renderJson(map);
        } else {
            controller.renderData(0, "投票失败");
        }
    }

    public void test1(){
        int eventId = 1;
        User user = User.dao.findById(getPara("userId"));

        if(isActiveUser(user)) {
            renderData(0, "用户不存在或未关注");
            return;
        }
        EventAttend eventAttend = EventAttend.dao.findById(eventId);
        if (isActiveEvent(eventAttend)) {
            renderData(0, "活动已结束,或未开始！");
            return;
        }

        EventSustain eventSustain = EventSustain.dao.findFirst("SELECT * FROM event_sustain WHERE user_id = ?", user.getId());
        //判断投票者是存在投票次数，投票次数为一
        if (eventSustain != null) {
            //提示用户已无投票权
            renderData(0, "每人仅能给一位好友加油哦！送您一张满1000减50优惠券(券码:" + Constant.Event.COUPON_CODE + ")");
            return;
        }

        //剩余点击次数
        int restClickAmount = eventAttend.getRestClickAmount();
        //随机里程数
        Integer value = 0;
        if (restClickAmount > 0) {
            update(this, user, eventId);
        } else {
            //投票已完成
            renderData(0, "投票已结束");
            return;
        }
    }
*/
    public void test() throws IOException {

/*        List<EventAttend> list = EventAttend.dao.find("SELECT * FROM event_attend");
        for(EventAttend ea : list){
            ea.setClickAmount(ea.getClickAmount() - 50);
            ea.setRestClickAmount(ea.getRestClickAmount() - 50);
            if(ea.update()){
                System.out.println("成功："+ea.getId());
            }else{
                System.out.println("失败："+ea.getId());
            }
        }*/

       /* User user = User.dao.findById(getPara("userId"));
        synchronized (this){

            Map<String, Object> map = new HashMap<String, Object>();
            if (user != null && user.getStatusId() == 1) {

                EventAttend eventAttend = EventAttend.dao.findById(1);
                //判断活动是否有效
                if (eventAttend != null) {
                    Event event = Event.dao.findFirst("SELECT * FROM event WHERE id =? AND start_time <= NOW() AND NOW() < end_time", eventAttend.getEventId());
                    //判断活动是否有效
                    if (event == null) {
                        map.put("code", 0);
                        map.put("message", "活动已结束,或未开始！");
                        renderJson(map);
                        return;
                    }
                    EventSustain eventSustain = EventSustain.dao.findFirst("SELECT * FROM event_sustain WHERE user_id = ?", user.getId());
                    //判断投票者是存在投票次数，投票次数为一
                    if (eventSustain != null) {
                        //提示用户已无投票权
                        map.put("code", 0);
                        map.put("message", "每人仅能给一位好友加油哦！送您一张满1000减50优惠券(券码:" + Constant.Event.COUPON_CODE + ")");
                        renderJson(map);
                        return;
                    }
                    //剩余点击次数
                    int restClickAmount = eventAttend.getRestClickAmount();
                    //随机里程数
                    Integer value = 0;
                    if (restClickAmount == 1) {
                        //得出最后里程数，结束投票，更新完成投票时间
                        value = eventAttend.getDisanceRest();
                    } else if (restClickAmount > 0) {
                        //开始 计算 随机里程参与投票
                        //value = getRandom(eventAttend.getDisanceRest(), eventAttend.getRestClickAmount());
                    } else if (restClickAmount < 0) {
                        map.put("code", 0);
                        map.put("message", "已超过投票次数，投票无效");
                        renderJson(map);
                        return;
                    } else {
                        //投票已完成
                        map.put("code", 0);
                        map.put("message", "投票已结束");
                        renderJson(map);
                        return;
                    }
                    eventSustain = new EventSustain();
                    eventSustain.setUserId(user.getId());
                    eventSustain.setAttendId(eventAttend.getId());
                    eventSustain.setValue(value);
                    eventSustain.setCreateTime(new Date());
                    if (eventSustain.save()) {
                        eventAttend.setRestClickAmount(restClickAmount - 1);
                        Integer tag = eventAttend.getDisanceRest() - value;
                        if (tag <= 0) {
                            tag = 0;
                            eventAttend.setCompleteTime(new Date());
                        }
                        eventAttend.setDisanceRest(tag);
                        eventAttend.update();
                        //提示投票成功
                        User targetUser = User.dao.findById(eventAttend.getUserId());
                        Map<String, Object> result = new HashMap<String, Object>();
                        map.put("value", eventSustain.getValue());
                        map.put("username", targetUser.getWechatNickname());
                        map.put("couponCode", Constant.Event.COUPON_CODE);//安慰奖
                        map.put("code", 1);//操作结果代码
                        renderJson(map);
                    } else {
                        map.put("code", 0);
                        map.put("message", "投票失败");
                        renderJson(map);
                    }
                } else {
                    //todo 提示错误
                    map.put("code", 0);
                    map.put("message", "投票失败");
                    renderJson(map);
                }

            } else {
                map.put("code", 0);
                map.put("message", "用户不存在或未关注");
                renderJson(map);
            }
        }*/


/*
        int i = 0;
        int f = 0;
        List<String> non_existent = new ArrayList<>();
        try {
            List<Photo> listPhotos = Photo.dao.find("SELECT * FROM photo WHERE type_id = 14 ");
            for (Photo photo : listPhotos) {
                String photoPath = "D:/website/mulan_xxl/static/view-img/"+photo.getPath() ;
                File photoFile = new File(photoPath);
                if (photoFile.exists()) {
                    Thumbnails.of(photoPath)
                            .size(240, 160)
                            .toFile("D:/website/mulan_xxl/static/thumbnail/"+photo.getPath()) ;
                }else{
                    f++;
                    non_existent.add(photo.getPath());
                }
                i++;
                System.out.println("---已处理：" + i + "张图片"+";不存在："+f+"张图片");
            }
            System.out.println("-----------共处理：" + i + "张图片"+";不存在："+f+"张图片");
            System.out.println(StringUtil.join(non_existent,","));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("-----------共处理：" + i + "张图片"+";不存在："+f+"张图片");
            System.out.println(StringUtil.join(non_existent,","));
        }*/


        /**
         * 获取所有客服基本信息
         */
        /*String url = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", TokenHandler.getAccessToken());
        Map<String, Object> data = new HashMap<String, Object>();
        List<Map> list = new ArrayList<>();

        CloseableHttpClient client = null;
        CloseableHttpResponse resp = null;
        try {
            client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            post.addHeader("Content-type", "application/json");
            StringEntity entity = new StringEntity("", ContentType.create("application/json", "UTF-8"));
            post.setEntity(entity);
            resp = client.execute(post);
            int statusCode = resp.getStatusLine().getStatusCode();
            if (statusCode >= 200 && statusCode < 300) {
                String str = EntityUtils.toString(resp.getEntity(), "utf-8");
                data = JSONObject.parseObject(str);
                list = (List<Map>) data.get("kf_list");
                for (Map map : list) {
                    String kf_account = map.get("kf_account") + "";
                    String kf_nick = map.get("kf_nick") + "";
                    String kf_id = map.get("kf_id") + "";
                    String kf_headimgurl = map.get("kf_headimgurl") + "";
                    String kf_wx = map.get("kf_wx") + "";
                    String invite_expire_time = map.get("invite_expire_time") + "";
                    CustomerService service = new CustomerService();
                    service.setKfAccount(kf_account);
                    service.setKfNick(kf_nick);
                    service.setKfHeadimgurl(kf_headimgurl);
                    service.setKfId(kf_id);
                    service.setKfWx(kf_wx);
                    service.setInviteExpireTime(invite_expire_time);
                    service.setCreateTime(new Date());
                    service.save();
                }
            }
        } catch (Exception ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                client.close();
                resp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/


        //生成缩略图
        /*List<Photo> lists = Photo.dao.find("SELECT * FROM photo WHERE type_id = 14");
        List<String> photosName = new ArrayList<>();
        int i = 0 ;
        for(Photo photo : lists){
            Thumbnails.of("D:/website/mulan_xxl/static/view-img/"+photo.getPath())
                    .size(240, 160)
                    .toFile("D:/website/mulan_xxl/static/thumbnail/"+photo.getPath()) ;
            System.out.println("正在处理第："+i+"张图片");
        }
        System.out.println(StringUtil.join(photosName,","));*/


        //修改汇率
        /*float exchangeRate = 5.2F;
        List<Ticket> lists  = Ticket.dao.find("SELECT * FROM ticket");
        int total = 0;
        int s = 0 ;
        int f = 0;
        for(Ticket ticket : lists){
            *//*total++;
            float lastPrice = ticket.getNzdPrice() * exchangeRate;
            BigDecimal d=new BigDecimal(lastPrice);
            float e=d.setScale(0, RoundingMode.HALF_UP).floatValue();
            ticket.setPrice(lastPrice);

            float lastOldPrice = ticket.getOldNzdPrice() * exchangeRate;
            BigDecimal o = new BigDecimal(lastOldPrice);
            float oo = o.setScale(0,RoundingMode.HALF_UP).floatValue();
            ticket.setOldPrice(lastOldPrice);
            if(ticket.update()){
                System.out.println("成功------------"+ticket.getId()+"----------------"+total);
                s++;
            }else{
                System.out.println("失败------------"+ticket.getId()+"----------------"+total);
                f++;
            }*//*
            ticket.setOldPrice(Float.parseFloat(Math.round(ticket.getOldPrice())+""));
            ticket.setPrice(Float.parseFloat(Math.round(ticket.getPrice())+""));
            if(ticket.update()){
                System.out.println("成功------------"+ticket.getId()+"----------------"+total);
                s++;
            }else{
                System.out.println("失败------------"+ticket.getId()+"----------------"+total);
                f++;
            }
        }
        System.out.println("共计处理数据："+total+"条，其中成功："+s+"条，"+"失败："+f+"条");
*/


        //发送支付成功提示模板
        /*SentModelMessageHandler.sentSuccessPayModel("123", "test","test",
                "test", "test",new Date(),"oULNBwOvt_D2A_8se1bQOQ06ky0w",1);*/


       /* User user2 = UserController.getUserDetail("oULNBwLnqbvg6hbF3vLBdouSCzzc");
        user2.update();*/

       /* UserController.synchronizationUserInfo("oULNBwMD0wAFm5F_2FMIXqyRwE0w");*/

        //测试打款功能
        /*PaymentSeller.paymentSeller("cai_text_2","oULNBwPHPxM_hSynJhplf4XXbf4A","蔡明东", 10);*/

        //SentModelMessageHandler.sentRefundModel("oULNBwOvt_D2A_8se1bQOQ06ky0w",101F);

        /*List<Ticket> list = Ticket.dao.find("SELECT * FROM ticket");
        for(Ticket ticket : list){
            String tt = ticket.getDescription().replace("<br/>","\n");
            ticket.setDescription(tt);
            if(ticket.update()){
                System.out.println("******************-"+ticket.getId());
                System.out.println("##################-"+ticket.getDescription());
            }
        }*/


    }

    public boolean tt(String inputPath, String outputPath) throws IOException {
        Thumbnails.of(inputPath)
                .size(120, 80)
                .toFile(outputPath);
        return true;
    }

    /**
     * 获取用户openid（待加密）并设置在session中
     */
    public void getAuthority() {
        HttpServletRequest request = super.getRequest();
        HttpServletResponse response = super.getResponse();
        if (StrKit.notBlank(request.getParameter("code"))) {
            String code = request.getParameter("code");
            String para = GetHandler.get(Constant.WeChatFinalValue.getWebAuthorizeAccessToken(code));
            Map<String, String> mapPara = WxParaFormatter.jsonToMap(para);
            if (mapPara.containsKey("errcode")) {
                renderJsp("/view/menu2/ticket/confirm_pay.jsp");
            } else {
                String state = request.getParameter("state");
                super.setSessionAttr("openId", mapPara.get("openid"));
                if ("order".equals(state)) {
                    super.redirect("/view/menu3/order/index.jsp");
                } else if ("collection".equals(state)) {
                    super.redirect("/view/menu3/collection/index.jsp");
                } else if ("ticket".equals(state)) {
                    super.redirect("/view/menu2/ticket/index.jsp");
                } else if ("chartered".equals(state)) {
                    //super.redirect("/view/menu2/chartered/index.jsp");

                }else if("visa".equals(state)) {
                    super.redirect("/view/menu2/visa/index.jsp");
                }else if ("hot_commodity".equals(state)) {
                    super.redirect("/view/menu1/hot_commodity/index.jsp");
                }
            }
        }
    }

    public void load() {
        HttpServletRequest request = super.getRequest();
        HttpServletResponse response = super.getResponse();
        //判断访问方式
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        if (isGet) {
            //进行认证
            access(request, response);
        } else {
            try {
                //转码UTF-8,防止乱码
//                request.setCharacterEncoding("gbk");
//                response.setCharacterEncoding( "gbk" );
                //处理微信post请求
                //acceptMessage();
                getXmlPara2();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void parse(String protocolXML) {

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(protocolXML)));

            Element root = doc.getDocumentElement();
            NodeList books = root.getChildNodes();
            if (books != null) {
                for (int i = 0; i < books.getLength(); i++) {
                    Node book = books.item(i);
                    System.out.println("节点=" + book.getNodeName() + "\ttext=" + book.getFirstChild().getNodeValue());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 有乱码
     *
     * @return
     * @throws IOException
     */
    public Map<String, String> getXmlPara3() throws IOException {
        HttpServletRequest req = getRequest();
        req.setCharacterEncoding("utf-8");
        BufferedReader br = null;
        br = new BufferedReader(new InputStreamReader(req.getInputStream()));
        String str = null;
        StringBuffer sb = new StringBuffer();
        while ((str = br.readLine()) != null) {
            sb.append(str);
        }

        String xml = sb.toString();
        try {
            Map<String, String> maps = new HashMap<String, String>();
            org.dom4j.Document document = org.dom4j.DocumentHelper.parseText(xml);
            org.dom4j.Element root = document.getRootElement();
            List<org.dom4j.Element> eles = root.elements();
            for (org.dom4j.Element e : eles) {
                maps.put(e.getName(), e.getTextTrim());
            }
            return maps;
        } catch (org.dom4j.DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 无乱码，将所有字母转换成了小写
     */
    public void getXmlPara2() throws Exception {
        try {
            org.jsoup.nodes.Document doc = org.jsoup.Jsoup.parse(getRequest().getInputStream(), "utf-8", "");
            String tt = doc.body().toString().replace("<body>", "").replace("</body>", "").replace("\n", "").replace("\t", "").replace("\r", "").replace(" ", "");
            System.out.println(tt);
            Map<String, String> test = WxParaFormatter.xmlToMap(tt);
            msgRoute(test);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 乱码
     *
     * @throws IOException
     */
    public void getXmlPara() throws Exception {
        java.io.BufferedReader bis = new java.io.BufferedReader(new java.io.InputStreamReader(getRequest().getInputStream()));

        String line = null;
        String result = "";

        try {
            while ((line = bis.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(result);
            Map<String, String> test = WxParaFormatter.xmlToMap(result);
            bis.close();
            msgRoute(test);
            //String yy = test.get("Content").toString() ;
            //renderText(yy);
        }
    }

    public void msgRoute(Map<String, String> para) throws IOException {
        String msgType = para.get("MsgType".toLowerCase());
        String openid = para.get("FromUserName".toLowerCase());
        Map<String, String> rePara = new HashMap<String, String>();
        rePara.put("ToUserName", openid);
        rePara.put("FromUserName", para.get("ToUserName".toLowerCase()));
        rePara.put("CreateTime", new Date().getTime() + "");
        rePara.put("MsgType", Constant.WeChatFinalValue.MSG_TEXT_TYPE);
        if (Constant.WeChatFinalValue.MSG_TEXT_TYPE.equals(msgType)) {
            //文字消息推送
            String tt;
            String content = para.get("Content".toLowerCase());
            if ("活动".equals(content)
                    ||"摄影".equals(content)
                    ||"摄影大赛".equals(content)
                ) {
                //回复图片消息
/*
                rePara.put("MsgType", Constant.WeChatFinalValue.MSG_IMAGE_TYPE);
                rePara.put("Image", "$Image$");
                tt = WxParaFormatter.mapToXml(rePara).replace("$Image$", "<MediaId>_IQ8Dtoxwwd7WyoSlB7PQPOklKTDcxpR5uPjpAFLPTM</MediaId>");
*/

                //回复图文消息类型
                /*Map<String, Object> rePara1 = new HashMap<String, Object>();
                rePara1.put("ToUserName", openid);
                rePara1.put("FromUserName", para.get("ToUserName".toLowerCase()));
                rePara1.put("CreateTime", new Date().getTime() + "");
                rePara1.put("MsgType", Constant.WeChatFinalValue.RESP_MESSAGE_NEWS_TYPE);
                rePara1.put("ArticleCount", "1");//图文消息个数，限制为8条以内
                Map<String, String> item = new HashMap<String, String>();
                item.put("Title", "新途：加油新西兰！");
                item.put("Description", "对不起，是我没管好老板 ～\n他又要送福利了！");
                item.put("PicUrl", "http://mmbiz.qpic.cn/mmbiz_png/hGCHoI1IWUgbR7ef8kicDL3ndLf01YpQkTGgrGs7bMLB2zBoQwfxE02ETyGwibWJ6Caj7TaDwOxJ9p0ricZFbImGQ/0?wx_fmt=png");
                item.put("Url", "https://mp.weixin.qq.com/s?__biz=MzIyNTUzMTIxNg==&mid=100000171&idx=1&sn=c4dc8f6c0e050e274078b63adbf5f40e&chksm=687f05945f088c822bd900618c62c6d31d994d47fb88f0f654e499b04fbc0ea7f70c3f7db4c6#rd");
                Map<String, String> articles = new HashMap<String, String>();
                articles.put("item", "$item$");
                rePara1.put("Articles", "$articles$");
                tt = WxParaFormatter.mapToXml2(rePara1)
                        .replace("$articles$", WxParaFormatter.mapToXml(articles).replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").replace("<xml>", "").replace("</xml>", ""))
                        .replace("$item$", WxParaFormatter.mapToXml(item).replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").replace("<xml>", "").replace("</xml>", ""))
                ;*/
                String title = "Stunning NZ｜留住新西兰摄影活动第二期";
                String desc = "留住新西兰摄影活动第二期投稿通道已开启~";
                String photoPath = "http://mmbiz.qpic.cn/mmbiz_jpg/hGCHoI1IWUhm2MX57wweibxTBOOOKIXhoxDibiaib71VZILPlVibYaUL9Mib6jyiaomd5gud2VFgq8vow4NemtNuL6iaJg/0?wx_fmt=jpeg";
                String newPath = "https://mp.weixin.qq.com/s?__biz=MzIyNTUzMTIxNg==&mid=100000262&idx=1&sn=d1e6aa1d03e7b183893023a69e603179&chksm=687f06395f088f2fcbcd26872464f2ebfb576c83a42b2483548be42cb26083feae5afbabc013#rd";
                //发送图文消息
                tt = sentNews(openid,para.get("ToUserName".toLowerCase()),title,desc,photoPath,newPath);
                //群发图文消息
                //SentModelMessageHandler.sentNewsModel(openid);
            }else if("优惠券".equals(content)){
                //回复图片类型消息
                Map<String, Object> rePara1 = new HashMap<String, Object>();
                rePara1.put("ToUserName", openid);
                rePara1.put("FromUserName", para.get("ToUserName".toLowerCase()));
                rePara1.put("CreateTime", new Date().getTime() + "");
                rePara1.put("MsgType", Constant.WeChatFinalValue.MSG_IMAGE_TYPE);
                Map<String, String> item = new HashMap<String, String>();
                rePara1.put("Image", "$Image$");
                item.put("MediaId", "_IQ8Dtoxwwd7WyoSlB7PQK_1SRKu_B5e0YTKI89v_54");
                tt = WxParaFormatter.mapToXml2(rePara1)
                        .replace("$Image$",WxParaFormatter.mapToXml(item).replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "")
                                .replace("<xml>", "").replace("</xml>", ""));
            } else {
                //回复文本类型消息
                String sentContent = TextMsgController.routeMsg(content);
                if(sentContent != null){
                    rePara.put("MsgType", "text");
                }else{
                    rePara.put("MsgType", "transfer_customer_service");
                    sentContent = "留言成功，我们的工作人员将尽快帮您处理。";
                }
                //rePara.put("KfAccount","kf2002@nzasst");
                rePara.put("Content", sentContent);
                tt = WxParaFormatter.mapToXml(rePara);
            }

            //保存聊天记录
            Boolean result = ChatHistoryController.save(para.get("content"), msgType, para.get("tousername"), para.get("fromusername"), Long.parseLong(para.get("createtime")));

            System.out.print(tt);
            getResponse().setContentType("application/xml;charset=UTF-8");
            getResponse().setCharacterEncoding("UTF-8");
            //getResponse().getWriter().write(tt);
            renderText(tt);
        } else if (Constant.WeChatFinalValue.MSG_IMAGE_TYPE.equals(msgType)
                || Constant.WeChatFinalValue.MSG_VOICE_TYPE.equals(msgType)
                || Constant.WeChatFinalValue.MSG_VIDEO_TYPE.equals(msgType)
                || Constant.WeChatFinalValue.MSG_SHORTVIDEO_TYPE.equals(msgType)
                || Constant.WeChatFinalValue.MSG_LOCATION_TYPE.equals(msgType)
                || Constant.WeChatFinalValue.MSG_LINK_TYPE.equals(msgType)) {
            //除文本外所有用户向公众号发送的消息推送
            rePara.put("Content", "留言成功，我们的工作人员将尽快帮您处理。");
            String tt = WxParaFormatter.mapToXml(rePara);
            System.out.print(tt);
            getResponse().setContentType("application/xml;charset=UTF-8");
            getResponse().setCharacterEncoding("UTF-8");
            //getResponse().getWriter().write(tt);
            renderText(tt);
        } else if (Constant.WeChatFinalValue.MESSAGE_EVENT_TYPE.equals(msgType)) {
            //事件推送
            String eventType = para.get("Event".toLowerCase());
            if (Constant.WeChatFinalValue.EVENT_SUBSCRIBE_TYPE.equals(eventType)) {
                //回复文本类型消息
                rePara.put("MsgType", Constant.WeChatFinalValue.MSG_TEXT_TYPE);
                UserHandler.subscribe(openid);
                System.out.println("用户关注成功，openid为:" + openid);
                /*rePara.put("Content", "Hi，欢迎关注新西兰微助手，我们将为您提供新西兰最有性价比的门票，餐饮，购物，包车，陪游等服务。祝您在新西兰旅途愉快。（回复“活动”查看最新优惠）");*/
                /*rePara.put("Content", "Hi，欢迎关注新西兰微助手，我们将为您提供新西兰最有性价比的门票，签证；即将推出餐饮，购物，包车，陪游等服务。祝您在新西兰旅途愉快。（回复“活动”查看摄影大赛，回复“优惠券”获取新人礼包）");*/
                rePara.put("Content", "Hi，欢迎关注新西兰微助手，我们将为您提供新西兰最有性价比的门票，签证；即将推出餐饮，购物，包车，陪游等服务。祝您在新西兰旅途愉快。（回复“摄影大赛”报名摄影作品，回复“活动”查看最新活动详情，回复“投票”查看最新投票，回复“优惠券”获取新人礼包）");
                String tt = WxParaFormatter.mapToXml(rePara);
                renderText(tt);
            } else if (Constant.WeChatFinalValue.EVENT_UNSUBSCRIBE_TYPE.equals(eventType)) {
                UserHandler.unSubscribe(openid);
                System.out.println("用户取消关注成功，openid为:" + openid);
            } else if (Constant.WeChatFinalValue.MSG_LOCATION_TYPE.equals(eventType)) {
                UserHandler.setLocation(openid, para.get("longitude"), para.get("latitude"), para.get("precision"));
            } else if (Constant.WeChatFinalValue.EVENT_CLICK_TYPE.equals(eventType)) {
                String eventKey = para.get("EventKey".toLowerCase());
                if ("coupon".equals(eventKey)) {
                    /*PrintWriter out = getResponse().getWriter();
                    out.print("优惠券将在活动期间进行推送，请尽请留意");*/
                    rePara.put("MsgType", Constant.WeChatFinalValue.MSG_IMAGE_TYPE);
                    rePara.put("Image", "$Image$");
                    String tt = WxParaFormatter.mapToXml(rePara).replace("$Image$", "<MediaId>_IQ8Dtoxwwd7WyoSlB7PQK_1SRKu_B5e0YTKI89v_54</MediaId>");
                    renderText(tt);
                } else if ("service".equals(eventKey)) {
                    rePara.put("Content", "您可以在对话框直接输入文字向我们提问，客服看到留言后会第一时间回复解答。");
                    String tt = WxParaFormatter.mapToXml(rePara);
                    renderText(tt);
                } else if ("chartered".equals(eventKey)) {
                    rePara.put("Content", "此功能正在开发中,敬请期待");
                    String tt = WxParaFormatter.mapToXml(rePara);
                    renderText(tt);
                }
            }
        }
    }

    /**
     * 验证URL真实性
     *
     * @return String
     */
    private String access(HttpServletRequest request, HttpServletResponse response) {
        // 验证URL真实性
        String signature = request.getParameter("signature");// 微信加密签名
        String timestamp = request.getParameter("timestamp");// 时间戳
        String nonce = request.getParameter("nonce");// 随机数
        String echostr = request.getParameter("echostr");// 随机字符串
        List<String> params = new ArrayList<String>();
        params.add(Token);
        params.add(timestamp);
        params.add(nonce);
        // 1. 将token、timestamp、nonce三个参数进行字典序排序
        Collections.sort(params, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
        String temp = HashKit.sha1(params.get(0) + params.get(1) + params.get(2));
        if (temp.equals(signature)) {
            System.out.println(echostr);
            renderText(echostr);
            return echostr;
        }
        return null;
    }

    //发送图文消息
    private String sentNews(String openid, String fromUserName,String title, String desc, String photoPath, String newPath )throws IOException{
        Map<String, Object> rePara1 = new HashMap<String, Object>();
        rePara1.put("ToUserName", openid);
        rePara1.put("FromUserName", fromUserName);
        rePara1.put("CreateTime", new Date().getTime() + "");
        rePara1.put("MsgType", Constant.WeChatFinalValue.RESP_MESSAGE_NEWS_TYPE);
        rePara1.put("ArticleCount", "1");//图文消息个数，限制为8条以内
        Map<String, String> item = new HashMap<String, String>();
        item.put("Title", title);
        item.put("Description", desc);
        item.put("PicUrl", photoPath);
        item.put("Url", newPath);
        Map<String, String> articles = new HashMap<String, String>();
        articles.put("item", "$item$");
        rePara1.put("Articles", "$articles$");
        String tt ="";
        tt =  WxParaFormatter.mapToXml2(rePara1)
                .replace("$articles$", WxParaFormatter.mapToXml(articles).replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").replace("<xml>", "").replace("</xml>", ""))
                .replace("$item$", WxParaFormatter.mapToXml(item).replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").replace("<xml>", "").replace("</xml>", ""))
        ;
        return tt;
    }

    public void getXmlPara4() throws Exception {
        StringBuilder xmlMsg = new StringBuilder();
        ServletInputStream in = getRequest().getInputStream();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1; ) {
            xmlMsg.append(new String(b, 0, n, "UTF-8"));
        }
        System.out.println(xmlMsg.toString());
        msgRoute(WxParaFormatter.xmlToMap(xmlMsg.toString()));
    }
//
//    private void acceptMessage() throws IOException {
//        HttpServletRequest request = super.getRequest();
//        HttpServletResponse response = super.getResponse();
//        // 处理接收消息
//        ServletInputStream in = request.getInputStream();
//        // 将POST流转换为XStream对象
//        XStream xs = SerializeXmlUtil.createXstream();
//        xs.processAnnotations(InputMessage.class);
//        xs.processAnnotations(OutputMessage.class);
//        // 将指定节点下的xml节点数据映射为对象
//        xs.alias("xml", InputMessage.class);
//        // 将流转换为字符串
//        StringBuilder xmlMsg = new StringBuilder();
//        byte[] b = new byte[4096];
//        for (int n; (n = in.read(b)) != -1; ) {
//            xmlMsg.append(new String(b, 0, n, "UTF-8"));
//        }
//        // 将xml内容转换为InputMessage对象
//        InputMessage inputMsg = (InputMessage) xs.fromXML(xmlMsg.toString());
//
//        String servername = inputMsg.getToUserName();// 服务端
//        String custermname = inputMsg.getFromUserName();// 客户端
//        long createTime = inputMsg.getCreateTime();// 接收时间
//        Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;// 返回时间
//
//        // 取得消息类型
//        String msgType = inputMsg.getMsgType();
//        // 根据消息类型获取对应的消息内容
//        if (msgType.equals(Constant.WeChatFinalValue.MSG_TEXT_TYPE)) {
//            // 文本消息
//            StringBuffer str = new StringBuffer();
//            str.append("<xml>");
//            str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>");
//            str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>");
//            str.append("<CreateTime>" + returnTime + "</CreateTime>");
//            str.append("<MsgType><![CDATA[" + msgType + "]]></MsgType>");
//            str.append("<Content><![CDATA[您发送的是:" + inputMsg.getContent() + "?]]></Content>");
//            str.append("</xml>");
//            response.getWriter().write(str.toString());
//        }
//        // 获取并返回多图片消息
//        else if (msgType.equals(Constant.WeChatFinalValue.MSG_IMAGE_TYPE)) {
//            System.out.println("获取多媒体信息");
//            String mediaId = inputMsg.getMediaId();//多媒体文件id
//            String picUrl = inputMsg.getPicUrl();//图片链接
//            long msgId = inputMsg.getMsgId();//消息id，64位整型
//
//            OutputMessage outputMsg = new OutputMessage();
//            outputMsg.setFromUserName(servername);
//            outputMsg.setToUserName(custermname);
//            outputMsg.setCreateTime(returnTime);
//            outputMsg.setMsgType(msgType);
//            ImageMessage images = new ImageMessage();
//            images.setMediaId(mediaId);
//            outputMsg.setImage(images);
//            response.getWriter().write(xs.toXML(outputMsg));
//        }
//        //事件
//        else if (msgType.equals(Constant.WeChatFinalValue.MESSAGE_EVENT_TYPE)) {
//            // 事件类型
//            String eventType = inputMsg.getEvent();
////            if (eventType.equals(WxMessageUtil.EVENT_TYPE_SUBSCRIBE)) {
////                // 关注
////            }else if (eventType.equals(WxMessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
////                //取消关注
////            }else if(eventType.equals(WxMessageUtil.EVENT_TYPE_CLICK)){
////                //点击
////            }
//        }
//    }
}
